package com.lq.ecoldchain.util

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.Image
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.ImageHeaderParserUtils
import com.lq.ecoldchain.base.view.App
import com.lq.ecoldchain.config.AppConfig
import kotlinx.android.synthetic.main.activity_verified.*

import java.io.File
import java.text.SimpleDateFormat
import java.util.*


object CameraUtil {
    lateinit var photoPath: String
    var file: File? = null
    //选择本地图片
    fun selectImageFromLocal(mContext: Context) {
        if (isSdCardExist()) {
            val intent: Intent
            if (Build.VERSION.SDK_INT < 19) {
                intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.type = "image/*"
            } else {
                intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            }
            (mContext as Activity).startActivityForResult(intent, AppConfig.REQUEST_CODE_SELECT_PICTURE)
        } else {
            toast { "暂无外部存储" }
        }

    }

    //照相
    fun takePhoto(mContext: Context) = if (isSdCardExist()) {
        photoPath = createAvatarPath("make_of_lq")
        val fileUri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(mContext,
                    AppConfig.authority, File(photoPath))
        } else {
            Uri.fromFile(File(photoPath))
        }
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
        try {
            (mContext as Activity).startActivityForResult(intent, AppConfig.REQUEST_CODE_TAKE_PHOTO)
        } catch (e: Exception) {
            toast { "摄像头暂未准备好" }
        }
    } else {
        toast { "暂无外部存储" }
    }

    private fun getOutputMediaFile(): File? {
        if (Environment.MEDIA_MOUNTED != Environment.getExternalStorageState()) {
            toast { "请检查内部存储" }
            return null
        }
        val mediaStorageDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "LionCloudVideo")
        if (!mediaStorageDir.exists()) {
            mediaStorageDir.mkdirs()
        }
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINESE).format(Date())
        file = File(mediaStorageDir.path + File.separator + "VID_" + timeStamp + ".mp4")
        return file
    }

    private fun createAvatarPath(s: String): String {
        val dir = AppConfig.PICTURE_DIR
        val destDir = File(dir)
        if (!destDir.exists()) {
            destDir.mkdirs()
        }
        file = File(dir, "${System.currentTimeMillis()}$s.png")
        return file!!.absolutePath
    }

    private fun isSdCardExist(): Boolean {
        return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED

    }

    fun handleSelectedPicture(data: Uri?): String? {
        if (data != null) {
            val imagePath: String
            val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = App.instance.contentResolver.query(data, filePathColumn, null, null, null)
            if (null == cursor) {
                val path = data.path
                val file = File(path)
                if (file.isFile) {
                    imagePath = path
                    return imagePath
                } else {
                    toast { "没有找到您想要的图片" }
                }
                return null
            } else {
                if (!cursor.moveToFirst()) {
                    toast { "没有找到您想要的图片" }
                    return null
                }
                val columnIndex = cursor.getColumnIndex(filePathColumn[0])
                val path = cursor.getString(columnIndex)
                if (path != null) {
                    val file = File(path)
                    return if (!file.isFile) {
                        toast { "没有找到您想要的图片" }
                        cursor.close()
                        null
                    } else {
                        imagePath = path
                        cursor.close()
                        imagePath
                    }
                }
            }
        }
        return null
    }

    fun handlePhoto(requestCode: Int, data: Uri?, view: ImageView?, listener: QiNiuUtils.OnQiNiuListener) {
        when (requestCode) {
            AppConfig.REQUEST_CODE_TAKE_PHOTO -> {
                QiNiuUtils.upload(CameraUtil.file!!.path, listener)
                if (view != null)
                    Glide.with(view.context).load(CameraUtil.file!!.path).into(view)
            }
            AppConfig.REQUEST_CODE_SELECT_PICTURE -> {
                if (data != null) {
                    val path = CameraUtil.handleSelectedPicture(data)
                    if (path != null) {
                        QiNiuUtils.upload(path, listener)
                        if (view != null)
                            Glide.with(view.context).load(path).into(view)
                    }
                }
            }
        }
    }
}
